package com.qmds.common.core.interceptor;

import com.qmds.common.core.annotation.NoLoginCheck;
import com.qmds.common.core.utils.JwtUtils;
import com.qmds.common.core.utils.UserUtils;
import io.jsonwebtoken.Claims;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * --- 代码敲烂 月薪过万 ---
 *
 * @author ShiJiaWei
 * @date 2024/8/20
 * @desc:
 */
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 判断访问的控制器的方法有没有使用指定的注解
        // springmvc中，控制器中的方法会封装成一个HandlerMethod对象
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            // 判断方法是否有指定的注解
            boolean ret = method.isAnnotationPresent(NoLoginCheck.class);
            // 如果有，说明不需要进行登录状态的判断，直接放行
            if (ret) {
                return true;
            }
            String token = request.getHeader("X-Token");
            if (token == null || token.isEmpty()) {
                throw new RuntimeException("请重新登录！");
            }
            try {
                Claims claims = JwtUtils.parseJWT(token);
                Object uid = claims.get("uid");
                // 将token中解析得到的用户id，保存到ThreadLocal中
                UserUtils.setId(Integer.valueOf(uid.toString()));
            } catch (Exception e) {
                throw new RuntimeException("请重新登录！");
            }
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 删除用户id
        UserUtils.removeId();
    }
}
